package com.example.timertasksynchronized

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.timertasksynchronized.ui.theme.TimerTaskSynchronizedTheme
import java.util.Timer
import java.util.TimerTask

class MainActivity : ComponentActivity() {

    val TAG = MainActivity::class.simpleName
    private val lockObject = Any()
    //定义Timer
    private var timer1: Timer? = null
    private var timer2: Timer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TimerTaskSynchronizedTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting("Android")
                }
            }
        }

        timer1 = Timer()
        timer1!!.schedule(object : TimerTask() {
            override fun run() {
                synchronized(lockObject) {  //用this的话没效果，换成lockObject就可以了
                    Log.d(TAG!!, "timer1--开始执行")
                    Thread.sleep(1000)
                    Log.d(TAG, "timer1--1s后继续执行")
                    Thread.sleep(1000)
                    Log.d(TAG, "timer1--1s后继续执行")
                    Thread.sleep(1000)
                    Log.d(TAG, "timer1--1s后继续执行")
                    Thread.sleep(1000)
                    Log.d(TAG, "timer1--1s后继续执行")
                }
            }
        }, 5 * 1000)

        timer2 = Timer()
        timer2!!.schedule(object : TimerTask() {
            override fun run() {
                synchronized(lockObject) {
                    Log.w(TAG!!, "timer2--开始执行")
                    Thread.sleep(1000)
                    Log.w(TAG, "timer2--1s后继续执行")
                    Thread.sleep(1000)
                    Log.w(TAG, "timer2--1s后继续执行")
                    Thread.sleep(1000)
                    Log.w(TAG, "timer2--1s后继续执行")
                    Thread.sleep(1000)
                    Log.w(TAG, "timer2--1s后继续执行")
                }
            }
        }, 5 * 1000)
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TimerTaskSynchronizedTheme {
        Greeting("Android")
    }
}